package com.beemans.common.app

import android.os.Build
import android.os.Handler
import android.os.Looper
import android.webkit.WebView
import androidx.annotation.CallSuper
import com.beemans.common.utils.AutoSize
import com.beemans.common.utils.CrashHandler
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ProcessUtils
import com.getkeepsafe.relinker.ReLinker
import com.tencent.mmkv.MMKV
import com.tiamosu.fly.base.BaseFlyApplication

/**
 * @author tiamosu
 * @date 2021/3/12
 */
abstract class CommonApp : BaseFlyApplication() {

    companion object {
        val globalHandler by lazy { Handler(Looper.getMainLooper()) }
    }

    abstract fun initFlavorConfig()

    @CallSuper
    open fun initSDK(isMainProcess: Boolean) {
        initMmkv()
        initLog()
    }

    override fun onCreate() {
        super.onCreate()
        AutoSize.init(this)
        CrashHandler.init()
        initFlavorConfig()
        initWebView()
        initSDK(ProcessUtils.isMainProcess())
    }

    protected open fun initMmkv() {
        val dir = getAppComponent().cacheFile().absolutePath + "/mmkv"
        MMKV.initialize(this, dir) { libName ->
            ReLinker.loadLibrary(this, libName)
        }
    }

    protected open fun initLog(logEnable: Boolean = true) {
        LogUtils.getConfig()
            .setLogSwitch(logEnable)
            .setConsoleSwitch(logEnable)
    }

    protected open fun initWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            // 安卓9.0后不允许多进程使用同一个数据目录
            val processName = ProcessUtils.getCurrentProcessName()
            if (!applicationContext.packageName.equals(processName)) {
                try {
                    WebView.setDataDirectorySuffix(processName)
                } catch (throwable: Throwable) {
                    throwable.printStackTrace()
                }
            }
        }
    }
}